package com.zhenyi.liuxue.mini;

import java.util.Date;

import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.liuxue.common.model.LxActivity;
import com.liuxue.common.model.LxFeedback;
import com.liuxue.common.model.LxUser;
import com.liuxue.common.model.LxUserActivity;
import com.zhenyi.liuxue.interceptor.AppAuthInterceptor;
import com.zhenyi.liuxue.interceptor.WXInterceptor;
import com.zhenyi.liuxue.interceptor.WechatInterceptor;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class ActivityController extends MiniController {

	/**
	 * H5 活动首页
	 */
	@Before({ AppAuthInterceptor.class, WXInterceptor.class })
	public void index() {
		render("/lx/activity/index.html");
	}

	/**
	 * H5 活动详情页
	 */
	// @Before({ AppAuthInterceptor.class, WXInterceptor.class,
	// WechatInterceptor.class })
	@Before({ AppAuthInterceptor.class, WechatInterceptor.class })
	public void detail() {
		Long id = getParaToLong("id");
		LxUser user = getH5User();
		if (id == null) {
			renderFailure(500, "id is null");
			return;
		}
		Kv kv = Kv.create();
		kv.set("activityId", id);
		kv.set("userId", user.getId());
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindActivity", kv);
		LxActivity info = LxActivity.dao.findFirst(sqlPara);
		if (info == null) {
			renderFailure(404, "activity not found");
			return;
		}
		Date startTime = info.getStartTime();
		Date endTime = info.getEndTime();
		info.put("time", DateUtil.format(startTime, "yyyy-MM-dd HH:mm") + "~" + DateUtil.format(endTime, "HH:mm"));
		setAttr("info", info);
		render("/lx/activity/info.html");
	}

	@Override
	public void list() {
		// LxUser user = getUser();
		// if (user == null) {
		// renderFailure(401, "please login");
		// return;
		// }
		LxUser user = getH5User();
		Kv kv = Kv.create();
		kv.set("userId", user.getId());
		kv.set("date", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindActivities", kv);
		String findSql = sqlPara.getSql();
		String totalRowSql = "select * from (" + findSql + ") as t";
		Page<LxActivity> pages = LxActivity.dao.paginateByFullSql(getPage(), PAGE_SIZE, totalRowSql, findSql,
				kv.get("date"), kv.get("date"), kv.get("userId"));
		int i = 0;
		while (i < pages.getList().size()) {
			LxActivity item = pages.getList().get(i);
			boolean isVisible = true;
			if (StrKit.notBlank(item.getVisibility())) {
				JSONObject visibility = JSONUtil.parseObj(item.getVisibility());
				// Iterator<Entry<String, Object>> it =
				// visibility.entrySet().iterator();
				// while (it.hasNext()) {
				// Entry<String, Object> entry = it.next();
				// System.out.println(entry.getKey() + ":" + entry.getValue());
				// /*if (!user.get(entry.getKey()).equals(entry.getValue())) {
				// isVisible = false;
				// break;
				// }*/
				// }
				if (!visibility.isNull("location")) {
					JSONObject location = visibility.getJSONObject("location");
					if (location.getBool("checked")) {
						JSONArray locationArray = location.getJSONArray("value");
						if (locationArray.size() > 0 && (user.getProvince() == null
								|| !user.getProvince().contains(locationArray.getStr(0)))) {
							isVisible = false;
						} else if (locationArray.size() > 1
								&& (user.getCity() == null || !user.getCity().contains(locationArray.getStr(1)))) {
							isVisible = false;
						}
					}
				}
				if (!visibility.isNull("companyId")) {
					JSONObject companyId = visibility.getJSONObject("companyId");
					if (companyId.getBool("checked")) {
						Long companyIdValue = companyId.getLong("value");
						if (user.getCompanyId() == null || !user.getCompanyId().equals(companyIdValue)) {
							isVisible = false;
						}
					}
				}
			}
			Long activityId = item.getId();
			if (!isActivityInRange(activityId)) {
				isVisible = false;
			}
			if (!isVisible) {
				pages.getList().remove(i);
				continue;
			}

			Date startTime = item.getStartTime();
			Date endTime = item.getEndTime();
			item.put("time", DateUtil.format(startTime, "yyyy-MM-dd HH:mm") + "~" + DateUtil.format(endTime, "HH:mm"));
			i++;
		}
		renderResult(pages);
	}

	@Override
	public void info() {
		Long id = getParaToLong("id");
		LxUser user = getUser();
		if (user == null) {
			renderFailure(401, "please login");
			return;
		}
		if (id == null) {
			renderFailure(500, "id is null");
			return;
		}
		Kv kv = Kv.create();
		kv.set("activityId", id);
		kv.set("userId", user.getId());
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindActivity", kv);
		LxActivity info = LxActivity.dao.findFirst(sqlPara);
		if (info == null) {
			renderFailure(404, "activity not found");
			return;
		}
		Date startTime = info.getStartTime();
		Date endTime = info.getEndTime();
		info.put("time", DateUtil.format(startTime, "yyyy-MM-dd HH:mm") + "~" + DateUtil.format(endTime, "HH:mm"));
		renderResult(info);
	}

	/**
	 * 报名表
	 */
	@Before({ AppAuthInterceptor.class, WXInterceptor.class })
	public void enroll() {
		Long activityId = getParaToLong("activityId");
		if (activityId == null) {
			renderFailure(500, "activity id is null");
			return;
		}
		LxActivity activity = LxActivity.dao.findById(activityId);
		if (activity == null) {
			renderFailure(404, "not found. invailid id");
			return;
		}
		LxUser user = getH5User();
		setAttr("activity", activity);
		setAttr("userName", user.getName());
		setAttr("mobile", user.getMobile());
		setAttr("email", user.getEmail());
		setAttr("job", user.getDepartment());
		// if (user.getLocation() != null && !",".equals(user.getLocation())) {
		// setAttr("province", user.getLocation().split(",")[0]);
		// setAttr("city", user.getLocation().split(",")[1]);
		// }
		setAttr("province", user.getProvince());
		setAttr("city", user.getCity());
		setAttr("companyId", user.getCompanyId());
		render("/lx/activity/enroll.html");
	}

	/**
	 * 提交报名
	 */
	@Override
	public void submit() {
		Long id = getParaToLong("id");
		String name = getPara("name");
		String mobile = getPara("mobile");
		String email = getPara("email");
		String birth = getPara("birth");
		String province = getPara("province");
		String city = getPara("city");
		Long companyId = getParaToLong("companyId");
		String job = getPara("job");
		String channel = getPara("channel");
		Integer prevSubmit = getParaToInt("prevSubmit", 0);
		Integer prevAdopt = getParaToInt("prevAdopt", 0);
		String question = getPara("question");
		// LxUser user = getUser();
		// if (user == null) {
		// renderFailure(401, "please login");
		// return;
		// }
		LxUser user = getH5User();
		if (id == null) {
			renderFailure(500, "id is null");
			return;
		}
		Kv kv = Kv.create();
		kv.set("activityId", id);
		kv.set("userId", user.getId());
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindUserActivity", kv);
		LxUserActivity info = LxUserActivity.dao.findFirst(sqlPara);
		if (info != null && info.getStatus().equals(1)) {
			renderFailure(500, "您已参加了此活动");
			return;
		}
		LxActivity activity = LxActivity.dao.findById(id);
		if (activity == null) {
			renderFailure(404, "活动不存在");
			return;
		}
		if (activity.getIsOver() != null && activity.getIsOver().equals(1)) {
			renderFailure(500, "活动已结束");
			return;
		}

		boolean flag = false;
		if (info == null) {
			info = new LxUserActivity();
			info.setUserId(user.getId());
			info.setActivityId(id);
			flag = info.save();
		}
		info.setStatus(1);
		info.setName(name);
		info.setMobile(mobile);
		info.setEmail(email);
		info.setBirth(birth);
		info.setProvince(province);
		info.setCity(city);
		info.setCompanyId(companyId);
		info.setJob(job);
		info.setChannel(channel);
		info.setPrevSubmit(prevSubmit);
		info.setPrevAdopt(prevAdopt);
		info.setQuestion(question);
		flag = info.update();
		if (flag) {
			// 报名成功 +100 积分
			user.setPoint(user.getPoint() + 100);
			user.update();
		}
		renderFlag(flag);
	}

	/**
	 * 参加活动
	 */
	public void attend() {
		LxUser user = getH5User();
		Long activityId = getParaToLong("activityId");
		if (activityId == null) {
			renderFailure(500, "user & activity id is needed");
			return;
		}
		LxActivity activity = LxActivity.dao.findById(activityId);
		if (activity == null) {
			renderFailure(404, "活动不存在");
			return;
		}
		if (activity.getIsOver() != null && activity.getIsOver().equals(1)) {
			renderFailure(500, "活动已结束");
			return;
		}
		LxUserActivity userActivity = LxUserActivity.dao.findById(activityId, user.getId());
		if (userActivity == null) {
			renderFailure(500, "请先报名活动");
			return;
		}
		userActivity.setAttend(1);
		userActivity.update();
		renderSuccess();
	}

	/**
	 * 反馈表
	 */
	@Before({ AppAuthInterceptor.class, WXInterceptor.class })
	public void feedback() {
		Long activityId = getParaToLong("activityId");
		setAttr("activityId", activityId);
		render("/lx/activity/feedback.html");
	}

	public void submitFeedback() {
		Long activityId = getParaToLong("activityId");
		String aboutTime = getPara("aboutTime");
		String aboutPlace = getPara("aboutPlace");
		String aboutFlow = getPara("aboutFlow");
		String bestSegment = getPara("bestSegment");
		Integer isNeeded = getParaToInt("isNeeded");
		String otherNeeds = getPara("otherNeeds");
		String suggestion = getPara("suggestion");
		Integer score = getParaToInt("score");

		LxFeedback feedback = new LxFeedback();
		feedback.setActivityId(activityId);
		feedback.setUserId(getH5User().getId());
		feedback.setAboutTime(aboutTime);
		feedback.setAboutPlace(aboutPlace);
		feedback.setAboutFlow(aboutFlow);
		feedback.setBestSegment(bestSegment);
		feedback.setIsNeeded(isNeeded);
		feedback.setOtherNeeds(otherNeeds);
		feedback.setSuggestion(suggestion);
		feedback.setScore(score);
		feedback.setAddTime();
		renderFlag(feedback.save());
	}
}
